#include "tcp_client_test.h"
#include "tcp_client.h"
#include "tcp_server.h"
#include "event_loop_thread.h"
#include <iostream>
#include "win_event_lock.h"

using namespace el;
using namespace std;

el::TcpClientTest::TcpClientTest()
{
	connect_ = 0;
	count_ = 0;
}

el::TcpClientTest::~TcpClientTest()
{
}

bool el::TcpClientTest::test()
{
	EventLoopThread thread;
	EventLoop *loop = thread.startLoop();

	SocketAddrIn addr(INADDR_LOOPBACK, 800);
	TcpServer* server = new TcpServer(loop, addr);
	server->setNewConnectionCallback(NewTcpConnectCallback(this, &TcpClientTest::onConnectInServer));
	server->setMessageCallback(TcpMessageCallback(this, &TcpClientTest::onMassageInServer));
	server->start();

	TcpClient client(loop, addr);
	client.setConnectionedCallback(TcpConnectedCallback(this, &TcpClientTest::onConnectInClient));
	client.setMessageCallback(TcpMessageCallback(this, &TcpClientTest::onMassageInClient));
	client.setCloseCallback(TcpCloseCallback(this, &TcpClientTest::onCloseInClient));
	client.connect();
	wait(2);
	assert(connect_);
	connect_->sendData("aaa", 4);
	wait(4);
	client.disconnect();
	wait(5);
	assert(!connect_);

	server->stop();
	server->release();
	Sleep(500);
	thread.quit();
	return true;
}

void el::TcpClientTest::wait(int n)
{
	while (true)
	{
		event_lock_.wait(10);
		MutexLockGuard mutex_(mutex_);
		if (count_ >= n)
		{
			break;
		}
	}
}

void el::TcpClientTest::onConnectInServer(TcpConnect * connect)
{
	cout << "server: connected." << endl;
	MutexLockGuard mutex_(mutex_);
	count_++;
	event_lock_.pulseEvent();
}

void el::TcpClientTest::onMassageInServer(TcpConnect * connect)
{
	Buffer buf;
	connect->readData(buf);
	cout << "server: connected." << buf.peekRead() << endl;
	connect->sendData(buf);
	MutexLockGuard mutex_(mutex_);
	count_++;
	event_lock_.pulseEvent();
}

void el::TcpClientTest::onConnectInClient(TcpConnect * connect)
{
	connect_ = connect;
	cout << "client: connected." << endl;
	MutexLockGuard mutex_(mutex_);
	count_++;
	event_lock_.pulseEvent();
}

void el::TcpClientTest::onMassageInClient(TcpConnect * connect)
{
	Buffer buf;
	connect->readData(buf);
	cout << "client: connected." << buf.peekRead() << endl;
	MutexLockGuard mutex_(mutex_);
	count_++;
	event_lock_.pulseEvent();

}

void el::TcpClientTest::onCloseInClient(TcpConnect * connect)
{
	connect_ = NULL;
	MutexLockGuard mutex_(mutex_);
	count_++;
	event_lock_.pulseEvent();
}

